package com.chanjiedata.changbs.module.count;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseActivity;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Mystock;
import com.chanjiedata.changbs.proto.Statistics;
import com.chanjiedata.changbs.utlis.DateUtil;
import com.chanjiedata.changbs.utlis.DialogUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class CountThirdFragment extends BaseFragment {

    Unbinder unbinder;
    @BindView(R.id.btn_day)
    RadioButton btnDay;
    @BindView(R.id.btn_week)
    RadioButton btnWeek;
    @BindView(R.id.btn_month)
    RadioButton btnMonth;
    @BindView(R.id.rg_date_type)
    RadioGroup rgDateType;
    @BindView(R.id.chart)
    LineChart chart;
    @BindView(R.id.tab_layout)
    TabLayout tablayout;
    @BindView(R.id.mPieChart)
    PieChart mPieChart;
    @BindView(R.id.tv_select_time)
    TextView tvSelectTime;
    @BindView(R.id.tv_shou_yi_text)
    TextView tvShouYiText;
    @BindView(R.id.tv_total_income)
    TextView tvTotalIncome;
    @BindView(R.id.tv_count_time)
    TextView tvCountTime;
    @BindView(R.id.tab_layout_two)
    TabLayout tabLayoutTwo;


    private String search_type = "1";  //  1 日  2 周  3 月
    private String type = "1";       // 1-总激活 2-机型A  3-机型B
    private String pieType = "1";    // 1-激活分布；2-总激活
    private String search_time_end = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    private DatePickerDialog.OnDateSetListener onDateSetListener;
    private List<Entry> entries = new ArrayList<>();
    private ArrayList<PieEntry> pieEntries = new ArrayList<>();
    private String[] pieColor;

    private List<Mystock.myMachine.List> datas = new ArrayList<>();

    private String[] titles_tow = {"激活机型分布", "累计总激活"};

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_count_third;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        tvSelectTime.setText(search_time_end);
        tvShouYiText.setText(DateUtil.getYear() + "年" + DateUtil.getMonth() + "月激活量");
        tvCountTime.setText(search_time_end);
        pieColor = getActivityContext().getResources().getStringArray(R.array.array_seven_color);
        initListener();
        initLineChart();
        initTabLayoutTwo();
        initPerChat();
        initXinahaoData();
        LoadLinedData();
        loadPerChartData();
    }

    private void initTabLayoutTwo() {
        for (int i = 0; i < titles_tow.length; i++) {
            tabLayoutTwo.addTab(tabLayoutTwo.newTab());
            tabLayoutTwo.getTabAt(i).setText(titles_tow[i]);
        }
        tabLayoutTwo.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab == null || tab.getText() == null) {
                    return;
                }
                scaleAnima(1.0f, 1.4f, tab.view);
                changePieType(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab.view == null || tab.getText() == null) {
                    return;
                }
                scaleAnima(1.4f, 1.0f, tab.view);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        scaleAnima(1.0f, 1.4f, tabLayoutTwo.getTabAt(0).view);
    }


    private void changePieType(int index) {
        switch (index) {
            case 0:
                pieType = "1";
                String[] split_day = search_time_end.split("-");
                tvShouYiText.setText(split_day[0] + "年" + split_day[1] + "月激活量");
                break;
            case 1:
                pieType = "2";
                tvShouYiText.setText("累计总激活");
                break;
        }
        loadPerChartData();
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        rgDateType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.btn_day:
                    search_type = "1";
                    tvCountTime.setText(search_time_end);
                    break;
                case R.id.btn_week:
                    search_type = "2";
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 6));
                    break;
                case R.id.btn_month:
                    search_type = "3";
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 29));
                    break;
            }
            LoadLinedData();
            loadPerChartData();
        });

        onDateSetListener = (datePicker, year, month, day) -> {
            search_time_end = year + "-" + (month + 1) + "-" + day;
            tvSelectTime.setText(search_time_end);
            if (pieType.equals("1")) tvShouYiText.setText(year + "年" + (month + 1) + "月激活");
            switch (search_type) {
                case "1":
                    tvCountTime.setText(search_time_end);
                    break;
                case "2":
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 6));
                    break;
                case "3":
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 29));
                    break;
            }
            LoadLinedData();
            if (pieType.equals("1"))  loadPerChartData();
        };
        tvSelectTime.setOnClickListener(v -> {
            DialogUtils.showDatePickerDialog(getActivity(), onDateSetListener, Calendar.getInstance());
        });

    }

    private void loadPerChartData() {
        Statistics.get_trading_month.Builder builder = Statistics.get_trading_month.newBuilder();
        builder.setMonth(search_time_end).setType(pieType);
        NetworkManager.INSTANCE.post(Apis.get_activation_month, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                List<Statistics.basis> lists = Statistics.get_trading_month.parseFrom(bytes).getListList();
                setPerChartData(lists, Statistics.get_trading_month.parseFrom(bytes).getTotalNum());
            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });
    }

    private void setPerChartData(List<Statistics.basis> lists, String totalNumber) {
        pieEntries.clear();
        ArrayList<Integer> colors = new ArrayList<Integer>();
        tvTotalIncome.setText(String.format("%s台", totalNumber));
        for (int i = 0; i < lists.size(); i++) {
            colors.add(Color.parseColor(pieColor[i]));
            if (Float.valueOf(totalNumber) == 0) {
                pieEntries.add(new PieEntry(1, lists.get(i).getName() + " " + lists.get(i).getNum() + "台"));
            } else {
                pieEntries.add(new PieEntry(Float.valueOf(lists.get(i).getNum()), lists.get(i).getName() + " " + lists.get(i).getNum() + "台"));
            }
        }
        PieDataSet dataSet = new PieDataSet(pieEntries, "");
        //设置饼状Item之间的间隙
        dataSet.setSliceSpace(2f);
        //数据和颜色
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setDrawValues(false);
        mPieChart.setData(data);
        //刷新
        mPieChart.animateXY(500, 500);
    }

    private void initPerChat() {
        mPieChart.setRotationEnabled(false);// 可以手动旋转
        mPieChart.setUsePercentValues(false);//显示成百分比
        mPieChart.setDrawEntryLabels(false);
        mPieChart.setTouchEnabled(false);
        mPieChart.setDrawCenterText(false);

        mPieChart.getDescription().setEnabled(false); //取消右下角描述
        //去掉半透明
        mPieChart.setTransparentCircleAlpha(0);
        mPieChart.getLegend().setEnabled(true);


        Legend l = mPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setFormSize(10);                      //设置图例的大小
        l.setFormToTextSpace(10f);              //设置每个图例实体中标签和形状之间的间距
        l.setForm(Legend.LegendForm.CIRCLE); //设置图例的形状

        l.setFormSize(13);                      //设置图例的大小

        l.setTextSize(13f);                      //设置图例标签文本的大小

        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);

        l.setXOffset(30);                      //设置比例块Y轴偏移量


        l.setXEntrySpace(30);

        l.setWordWrapEnabled(true);
    }

    /**
     * 初始化折线图tab
     */
    private void initTabLayout() {

        tablayout.addTab(tablayout.newTab());
        tablayout.getTabAt(0).setText("总激活");
        for (int i = 0; i < datas.size(); i++) {
            tablayout.addTab(tablayout.newTab());
            tablayout.getTabAt(i + 1).setText(datas.get(i).getGoodsSerial());
        }
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab == null || tab.getText() == null) {
                    return;
                }
                scaleAnima(1.0f, 1.4f, tab.view);
                ((BaseActivity) mContext).showProgress();
                changeType(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab.view == null || tab.getText() == null) {
                    return;
                }
                scaleAnima(1.4f, 1.0f, tab.view);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        scaleAnima(1.0f, 1.4f, tablayout.getTabAt(0).view);
    }


    private void scaleAnima(float v, float v2, TabLayout.TabView title) {
        AnimationSet animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(
                v, v2, v, v2,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(100);//动画持续时间
        animationSet.addAnimation(scaleAnimation);//保存动画效果到。。
        animationSet.setFillAfter(true);//结束后保存状态
        title.startAnimation(animationSet);//设置给控件

    }


    private void changeType(int index) {
        if (index == 0) {
            type = "1";
        } else {
            type = datas.get(index - 1).getGoodsId();
        }
        LoadLinedData();
    }

    private void LoadLinedData() {
        Statistics.get_increase.Builder builder = Statistics.get_increase.newBuilder();
        builder.setSearchType(search_type).setType(type).setSearchTimeEnd(search_time_end);
        NetworkManager.INSTANCE.post(Apis.get_activation_tend, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                ((BaseActivity) mContext).hideProgress();
                List<Statistics.basis> lists = Statistics.get_increase.parseFrom(bytes).getArrayList();
                setLineData(lists);
            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });
    }


    private void setLineData(List<Statistics.basis> lists) {
        //1.设置x轴和y轴的点
        entries.clear();
        for (int i = 0; i < lists.size(); i++)
            entries.add(new Entry(i, Float.valueOf(lists.get(i).getNum()), lists.get(i).getName()));
        LineDataSet dataSet = new LineDataSet(entries, "1"); // add entries to dataset
        dataSet.setColor(Color.parseColor("#8A9EC1FF"));//线条颜色
        dataSet.setCircleColor(Color.parseColor("#28AFE9"));//圆点颜色
        dataSet.setDrawFilled(true);  // 设置是否填充
        dataSet.setDrawCircleHole(false);  // 设置是否实心
        dataSet.setLineWidth(1.0f);//线条宽度
        dataSet.setValueTextColor(Color.parseColor("#28AFE9"));
        dataSet.setValueTextSize(9);
        //3.chart设置数据
        LineData lineData = new LineData(dataSet);
        chart.setData(lineData);
        chart.animateY(500); // refresh
    }

    private void initLineChart() {
        // 手势禁用
        chart.setTouchEnabled(false);
        Description description = new Description();
        description.setText("");
        chart.setDescription(description);
        //设置样式
        YAxis rightAxis = chart.getAxisRight();

        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);

        YAxis LeftAxis = chart.getAxisLeft();
        // 设置坐标轴的标签数量，当count>25时，count=25；当count<2时，count=2
        LeftAxis.setLabelCount(6);
        LeftAxis.setTextColor(Color.parseColor("#6F889C"));
        LeftAxis.setAxisMinimum(0); //设置Y轴是否从0开始

        //设置x轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setTextColor(Color.parseColor("#6F889C"));
        xAxis.setTextSize(11f);
        xAxis.setAxisMinimum(0f);
        xAxis.setDrawAxisLine(false);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setGridColor(Color.parseColor("#26070707"));
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置


        //透明化图例
        Legend legend = chart.getLegend();
        legend.setEnabled(false);
        xAxis.setGranularity(1);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                if (value < entries.size()) {
                    return entries.get((int) value).getData().toString();
                } else {
                    return "";
                }
            }
        });
    }


    @Override
    protected void init() {
    }


    private void initXinahaoData() {
        NetworkManager.INSTANCE.post(Apis.myMachine, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                datas = Mystock.myMachine.parseFrom(bytes).getListList();
                initTabLayout();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    public void reLoadData() {
        LoadLinedData();
        loadPerChartData();
    }

}
